package com.zhy.generator.codegen.mybatis.xmlmapper.element;

import com.zhy.generator.codegen.dom.xml.Attribute;
import com.zhy.generator.codegen.dom.xml.TextElement;
import com.zhy.generator.codegen.dom.xml.XmlElement;
import com.zhy.generator.codegen.mybatis.xmlmapper.XmlElementIdConstant;

/**
 * @author 源
 */
public class SelectAllElementGenerator extends AbstractXmlElementGenerator {
    public SelectAllElementGenerator() {
        super();
    }
    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("select");

        answer.addAttribute(new Attribute("id", XmlElementIdConstant.SELECT_ALL)); //$NON-NLS-1$

        answer.addAttribute(new Attribute("resultType", introspectedTable.getBaseRecordType()));

        answer.addAttribute(new Attribute("parameterType", "map"));


        StringBuilder sb = new StringBuilder();
        sb.append("select "); //$NON-NLS-1$

        answer.addElement(new TextElement(sb.toString()));
        answer.addElement(getBaseColumnListElement());
        if (introspectedTable.hasBLOBColumns()) {
            answer.addElement(new TextElement(",")); //$NON-NLS-1$
            answer.addElement(getBlobColumnListElement());
        }

        sb.setLength(0);
        sb.append("from "); //$NON-NLS-1$
        sb.append(introspectedTable.getIntrospectedTableName());
        answer.addElement(new TextElement(sb.toString()));

        XmlElement whereElement = new XmlElement("where");
        sb.setLength(0);
        sb.append(" where != null");
        XmlElement isNotNullElement = new XmlElement("if");
        isNotNullElement.addAttribute(new Attribute("test", sb.toString())); //$NON-NLS-1$
        TextElement whereText = new TextElement("${where}");
        isNotNullElement.addElement(whereText);
        whereElement.addElement(isNotNullElement);
        answer.addElement(whereElement);

        sb.setLength(0);
        sb.append(" orderby != null");
        XmlElement orderElement = new XmlElement("if");
        orderElement.addAttribute(new Attribute("test", sb.toString()));
        TextElement orderText = new TextElement("order by ${orderby}");
        orderElement.addElement(orderText);
        answer.addElement(orderElement);


        sb.setLength(0);
        sb.append(" limit != null");
        XmlElement limitElement = new XmlElement("if");
        limitElement.addAttribute(new Attribute("test", sb.toString()));
        TextElement limitText = new TextElement("limit ${limit}");
        limitElement.addElement(limitText);
        answer.addElement(limitElement);

        if (context.getPlugins().sqlMapSelectByPrimaryKeyElementGenerated(answer,introspectedTable)) {
            parentElement.addElement(answer);
        }

    }
}
